package com.ftqh.tutorial.security.entity;

import com.ftqh.tutorial.security.data.AbstractDomain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2016/12/27
 * \* Time: 14:08
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@Entity
@Table(name = "sys_security_user")
@EntityListeners(AuditingEntityListener.class)
@Data
@EqualsAndHashCode(callSuper=true,exclude = {"roles","groups"})
@ToString(exclude={"roles","groups"})
@NamedEntityGraph(name = "User.detail",
        attributeNodes = {@NamedAttributeNode("roles")})
public class User extends AbstractDomain<Integer> implements UserDetails {

    private static final long serialVersionUID = 3734144846353036677L;
    @Column(unique = true, nullable = false)
    private String username;
    @Column(unique = true)
    private String email;
    @Column(unique = true)
    private String phone;
    @Column(nullable = false)
    private String password;
    @Transient
    private String passwordConfirm;
    private String firstName;
    private String lastName;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name="sys_security_authority",
            joinColumns={@JoinColumn(name="USER_ID")},
            inverseJoinColumns={@JoinColumn(name="ROLE_ID")}
    )
    private Set<Role> roles = new HashSet<>();

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name="sys_security_group_user",
            joinColumns={@JoinColumn(name="USER_ID")},
            inverseJoinColumns={@JoinColumn(name="GROUP_ID")}
    )
    private Set<Group> groups = new HashSet<>();

    @Transient
    private Set<GrantedAuthority> authorities = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities.isEmpty()) {
            authorities.addAll(roles);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Transient
    public void addRoles(Set<Role> roles) {
        this.roles.addAll(roles);
    }
}
